package com.example.myapplication.music;

import static java.lang.Integer.parseInt;

import android.animation.ObjectAnimator;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication.R;

public class MusicActivity extends AppCompatActivity implements View.OnClickListener {
    //进度条
    private static SeekBar sb;
    private static TextView tv_progress,tv_total,name_song;
    //动画
    private ObjectAnimator animator;
    private MusicService.MusicControl musicControl;
    private String name;
    private Intent intent1,intent2;

    private MyServiceConn conn;

    private boolean isUnbind =false;
    private boolean isPlay =false;
    private int play_time=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_music);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.musicActivity), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        intent1=getIntent();
        init();
    }

    public void init(){
        tv_progress=(TextView)findViewById(R.id.tv_progress);
        //进度条的总长度，就是总时间
        tv_total=(TextView)findViewById(R.id.tv_total);
        //进度条的控件
        sb=(SeekBar)findViewById(R.id.sb);
        //歌曲名显示的控件
        name_song=(TextView)findViewById(R.id.song_name);
        //绑定控件的同时设置点击事件监听器
        findViewById(R.id.btn_previous).setOnClickListener(this);
        findViewById(R.id.btn_playOrPause).setOnClickListener(this);
        findViewById(R.id.btn_next).setOnClickListener(this);
        findViewById(R.id.btn_exit).setOnClickListener(this);

        name=intent1.getStringExtra("name");
        name_song.setText(name);

        intent2=new Intent(this,MusicService.class);
        conn=new MyServiceConn();
        bindService(intent2,conn,BIND_AUTO_CREATE);

        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(progress==seekBar.getMax())
                    animator.pause();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress=seekBar.getProgress();
                musicControl.seekTo(progress);

            }
        });

        ImageView iv_music=(ImageView)findViewById(R.id.iv_music);
        String position=intent1.getStringExtra("position");
        int i=parseInt(position);
        iv_music.setImageResource(frag1.icons[i]);
        //rotation和0f,360.0f就设置了动画是从0°旋转到360°
        animator=ObjectAnimator.ofFloat(iv_music,"rotation",0f,360.0f);
        animator.setDuration(10000);//动画旋转一周的时间为10秒
        animator.setInterpolator(new LinearInterpolator());//匀速
        animator.setRepeatCount(-1);//-1表示设置动画无限循环
    }

    public static Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bundle bundle=msg.getData();

            int duration=bundle.getInt("duration");
            int currentPosition=bundle.getInt("currentPosition");

            sb.setMax(duration);
            sb.setProgress(currentPosition);
            int minute=duration/1000/60;
            int second=duration/1000%60;
            String strMinute=null;
            String strSecond=null;

            if(minute<10)
                strMinute="0"+strMinute;
             else
                strMinute=strSecond+"";
            if(second<10)
                strSecond="0"+strSecond;
            else
                strSecond=strSecond+"";
            tv_total.setText(strMinute+":"+strSecond);
            //歌曲当前播放时长
            minute=currentPosition/1000/60;
            second=currentPosition/1000%60;
            if(minute<10){//如果歌曲的时间中的分钟小于10
                strMinute="0"+minute;//在分钟的前面加一个0
            }else{
                strMinute=minute+" ";
            }
            if (second<10){//如果歌曲中的秒钟小于10
                strSecond="0"+second;//在秒钟前面加一个0
            }else{
                strSecond=second+" ";
            }
            //显示当前歌曲已经播放的时间
            tv_progress.setText(strMinute+":"+strSecond);

        }
    };

    @Override
    public void onClick(View v) {
            if(v.getId()==R.id.btn_playOrPause){
                String position=intent1.getStringExtra("position");
                ImageView btn_playOrPause=(ImageView)findViewById(R.id.btn_playOrPause);
                int i=parseInt(position);
               if(play_time==0)
               {
                   musicControl.play(i);
                   animator.start();
                   play_time++;
               }
                if(isPlay){
                   musicControl.pausePlay();
                   animator.pause();
                   isPlay=false;
                    btn_playOrPause.setImageResource(R.drawable.ic_pause);
               }else {
                    musicControl.continuePlay();
                    animator.start();
                    isPlay=true;
                    btn_playOrPause.setImageResource(R.drawable.btn_play);
                }
            }
            if(v.getId()==R.id.btn_previous){
                String position=intent1.getStringExtra("position");
                int i=parseInt(position);
                if(i<2)
                {
                    i++;
                    musicControl.play(i);
                }
                else {
                    i=0;
                    musicControl.play(i);
                }
                animator.start();
            }
            if(v.getId()==R.id.btn_next){
                String position=intent1.getStringExtra("position");
                int i=parseInt(position);
                if(i>0)
                {
                    i--;
                    musicControl.play(i);
                }
                else {
                    i=2;
                    musicControl.play(i);
                }
                animator.start();

            }

    }

       class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicControl=(MusicService.MusicControl) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
    private void unbind(boolean isUnbind)
    {
        if(isUnbind)
            musicControl.pausePlay();
            unbindService(conn);
    }

    @Override
    protected void onDestroy() {
        unbind(isUnbind);
        super.onDestroy();
    }
}